package com.est.pc.interceptor;

import com.est.pc.domain.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * AdminInterceptor   拦截用户信息
 * 管理员拦截器
 */
public class AdminInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	        Object handler) throws Exception {
			Object obj = request.getSession().getAttribute("sys_user_key");//获取登录用户的key值
			//如果 requestedWith 为 null，则为同步请求。
			//如果 requestedWith 为 XMLHttpRequest 则为 Ajax 请求。
			String xrequest = request.getHeader("x-requested-with");

			//判断对象是否存在 否则直接回到 首页
			if (obj == null || !(obj instanceof UserInfo)) {
				if("XMLHttpRequest".equalsIgnoreCase(xrequest)) {//拦截AJAX请求
					response.setHeader("sessionstatus", "timeout");
				}else {
					response.sendRedirect(request.getContextPath() + "/system/login");//跳转到登录页面
				}
				return false;
			}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
	        ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
	        Object handler, Exception ex) throws Exception {
	}
}